# Author: Mr.Xu
# @Time : 2019/12/6 20:02
import time
from rest_framework import serializers
from django.conf import settings

from . import models
from course.models import Course
from libs.iPay import get_pay_url, alipay_gateway


class PayModelSerializer(serializers.ModelSerializer):
    # 商品的主键们：暂定 '1,2,3' 方式传多个主键
    goods_pks = serializers.CharField(max_length=32,required=True)
    class Meta:
        model = models.Order
        fields = ["subject","total_amount","pay_type","goods_pks"]
        extra_kwargs = {
            "total_amount": {
                "required" : True
            }
        }

    def validate(self, attrs):
        # 取出商品主键们
        goods_pks = attrs.pop("goods_pks")
        goods_pks = [pk for pk in goods_pks.split(",")]
            # raise serializers.ValidationError({"goods_pks","商品主键们格式错误"})
        course_objs = []

        # 根据商品主键得到总价
        total_price = 0
        for pk in goods_pks:
            try:
                # 先拿到课程对象，在得到价格。
                course_obj = Course.objects.get(pk=pk)
                course_objs.append(course_obj)
                total_price += course_obj.price
            except:
                raise serializers.ValidationError({"goods_pks", "错误的商品主键"})

        total_amount = attrs.get('total_amount')
        if total_amount != total_price:
            raise serializers.ValidationError({"total_amount", "商品总价被恶意篡改"})

        if not total_price:
            # 说明购买了免费课。可以直接入库也可以直接返回
            return attrs

        # 生成订单号
        order_on = self._get_order_no()
        # 订单名
        subject = attrs.get('subject')
        # 生成订单链接
        order_string = get_pay_url( # 使用自己封装的生成订单字符串的链接
            out_trade_no=order_on,
            total_amount=float(total_amount),
            subject=subject,
        )
        pay_url = alipay_gateway + order_string
        # 将支付链接保存在serializer对象中
        self.pay_url = pay_url

        # 添加额外的入口字段
        attrs["out_trade_no"] = order_on
        # 视图类给序列化类传参
        attrs['user'] = self.context.get('request').user

        # 将所有的商品对象存放在校验数据中，辅助订单详情表商品信息的入库
        attrs['course_objs'] = course_objs

        return attrs


    # 保存时触发
    def create(self, validated_data):
        # 从通过校验的数据中拿出课程对象们
        course_objs = validated_data.pop("course_objs")

        # 调用父类create保存订单数据
        order = super().create(validated_data)

        # 关系表操作
        order_detail_list = []
        for course in course_objs:
            order_detail_list.append(models.OrderDetail(order=order, course=course,
                                                        price=course.price, real_price=course.price))
        # 完成 订单详细表的批量插入
        models.OrderDetail.objects.bulk_create(order_detail_list)

        return order

    def _get_order_no(self):
        no = '%s' % time.time()
        return no.replace('.', '', 1)


class PaySuccessModelSerializer(serializers.ModelSerializer):
    pass


